package com.yulang.controller;

import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Controller
@RequestMapping("/")
public class IndexController {



    @PreAuthorize("hasAnyAuthority('sys:index')")
    @GetMapping
    public String index(Map<String,Object> map) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Object principal = authentication.getPrincipal();
        if(principal!=null && principal instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) principal;
            final String username = userDetails.getUsername();
            map.put("username",username);
        }
        return "index";
    }

    /**
     * 第二种方式获取已经登录的用户信息
     * @param authentication
     * @return
     */
    @ResponseBody
    @RequestMapping("/user/info")
    public Object userInfo(Authentication authentication) {
        return authentication.getPrincipal();
    }


    /**
     * 第三种获取已经登录的用户信息
     * @param userDetails
     * @return
     */
    @RequestMapping("/user/info2")
    public Object userInfo2(@AuthenticationPrincipal UserDetails userDetails) {
        return userDetails;
    }



}
